import React, { PureComponent } from 'react'
import { Button, message, Popconfirm } from 'antd'
import { connect } from '@umijs/max'
import list2tree from 'list2tree'
import {
 BreadcrumbBar, InputSearch, ProTable, ProTableOperate, ProTableOptions,
} from '@/components'
import styles from './index.less'
import RoleModal from './roleModal'
import { delRole, getMenuList, getRoleById } from './api'

const getNavTreeDataFunc = list2tree({
  idKey: 'id',
  parentIdKey: 'parentId',
  newKey: {
    key: 'id',
    name: 'menuName',
  },
})
const { OperateItem } = ProTableOperate
const menus = [{ name: '系统管理' }, { name: '角色管理' }]

@connect(({ global }) => ({ ...global }))
export default class Role extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      columns: [
        {
          title: '角色名称',
          dataIndex: 'roleName',
          width: '20%',
          key: 'roleName',
        },
        {
          title: '角色描述',
          dataIndex: 'roleDesc',
          width: '40%',
          key: 'des',
          render: (text, record) => (!text || text === '' ? '--' : text),
        },
        {
          title: '最近修改时间',
          dataIndex: 'updateTime',
          width: '15%',
          key: 'updateTime',
        },
        // {
        //   title: '最近修改人',
        //   dataIndex: 'updaterName',
        //   width: '15%',
        //   key: 'updaterName',
        // },
        {
          title: '操作',
          dataIndex: 'operation',
          width: '10%',
          key: 'operation',
          render: (text, record, index) => (
            <ProTableOptions>
              <span
                onClick={() => { this.onCheckClick(record) }}
                key="check"
              >
                查看
              </span>
              {
                !record.isSystem && (
                  <span
                    onClick={() => { this.onEditClick(record) }}
                    key="edit"
                  >
                    编辑
                  </span>
                )
              }
              {
                !record.isSystem && (
                  <Popconfirm
                    title="你确定要删除这个角色吗？"
                    okText="确定"
                    cancelText="取消"
                    onConfirm={() => this.onDeleteClick(record)}
                    key="delPop"
                  >
                    <span>
                      删除
                    </span>
                  </Popconfirm>
                )
              }
            </ProTableOptions>
          ),
        },
      ],
      menuList: [],
      query: {},
      loading: false,
    }

    this.modalRef = React.createRef()
  }

  componentDidMount() {
    this.getMenuList()
  }

  // 根据角色的menuList
  handleMenuList(record) {
    if (record && record.isSystem) {
      const handleFun = (arr) => arr.map((item) => {
        const obj = {
          name: item.menuName,
          key: item.id,
          check: false,
          edit: false,
        }
        const matchItem = record.menuList.find((ritem) => ritem.menuId === item.id)
        if (matchItem) {
          if (matchItem.readWriteStatus === 1) {
            obj.edit = true
            obj.check = true
          } else if (matchItem.readWriteStatus === 0) {
            obj.check = true
          }
        }
        if (item.children) obj.children = handleFun(item.children)
        return obj
      })
      return handleFun(this.state.menuList)
    }
    let checkList = []
    if (record && record.menuList) checkList = record.menuList
    const checkFun = (arr) => arr.map((item) => {
      const newItme = {
        name: item.menuName,
        key: item.menuId,
      }
      const obj = checkList.find((checkItem) => item.id === checkItem.menuId)
      if (obj) {
        if (obj.readWriteStatus === 1) {
          newItme.edit = true
          newItme.check = true
        } else if (obj.readWriteStatus === 0) {
          newItme.check = true
        }
      }
      if (item.children) newItme.children = checkFun(item.children)
      return newItme
    })
    return checkFun(this.state.menuList)
  }

  onEditClick = (record) => {
    getRoleById({ id: record.id }).then(
      (res) => {
        if (this.modalRef.current) this.modalRef.current.onEditOpen(res, this.handleMenuList(res))
      },
      (error) => {
        console.log(error)
      },
    )
  }

  onCheckClick = (record) => {
    getRoleById({ roleId: record.id }).then(
      (res) => {
        if (this.modalRef.current) this.modalRef.current.onCheckOpen(res, this.handleMenuList(res))
      },
      (error) => {
        console.log(error)
      },
    )
  }

  onDeleteClick = (record) => {
    this.setState({ loading: true })
    delRole({ id: record.id }).then(
      (res) => {
        message.success('删除角色成功')
        this.fetchData()
        this.setState({ loading: false })
      },
      (error) => {
        console.log(error)
        this.setState({ loading: false })
      },
    )
  }

  getMenuList = () => {
    getMenuList({ userId: this.props.user.id }).then(
      (res) => {
        this.setState({ menuList: getNavTreeDataFunc(res) })
      },
      (error) => {
        console.log(error)
      },
    )
  }

  showModal = () => {
    if (this.modalRef.current) this.modalRef.current.onNewOpen(this.handleMenuList())
  }

  fetchData = async () => {
    const { roleName } = this.state
    const tempQuery = {}
    if (roleName && roleName !== '') tempQuery.roleName = roleName
    this.setState({
      query: tempQuery,
    })
  }

  onCloseCallBack = () => {
    this.fetchData()
  }

  render() {
    const { loading } = this.state
    return (
      <div className={styles.page_content_with_breadcrumb}>
        <BreadcrumbBar menu={menus} />
        <div className={styles.page_content}>
          <div className={styles.page_content_right}>
            <ProTableOperate
              toggleOperate={false} // 是否隐藏 收起/展开 按钮 (如果隐藏按钮，handleToggleSta设置属性值不生效)
              unfolded // 默认展开状态
            >
              <OperateItem align="left">
                <InputSearch
                  placeholder="请输入关键词进行搜索"
                  value={this.state.roleName}
                  onChange={(e) => {
                    this.setState({
                      roleName: e.target.value,
                    }, () => {
                      this.fetchData()
                    })
                  }}
                  onSearch={this.fetchData}
                />
              </OperateItem>
              {/* <OperateItem itemType="btn">
                {
                  [
                    <Button
                      onClick={this.showModal}
                      type="primary"
                      loading={loading}
                      key="new"
                    >
                      新建角色
                    </Button>,
                  ]
                }
              </OperateItem> */}
            </ProTableOperate>
            <ProTable
              columns={this.state.columns}
              url="/api/v1/authority/role/listSysRole"
              query={this.state.query}
              loading={loading}
            />
          </div>
          <RoleModal
            ref={this.modalRef}
            closeCallBack={this.onCloseCallBack}
          />
        </div>
      </div>
    )
  }
}
